﻿/**
* ...
* @author Default
* @version 0.1
*/

package com.crlclr.common {
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.*;
	import com.crlclr.utils.*;	
	import flash.net.*;

	public class LoaderAdapter extends EventDispatcher implements ILoader {
		public var loader:*;
		public var info:String;
		public var path:String;
		public function LoaderAdapter(loader:*, path:String,info:String="未知") {
			this.path = path;
			this.info = info;
			this.loader = loader;
		}
		public function load():void {
			bindEvent(loader);
			var urlRequest:URLRequest = new URLRequest(this.path);
			loader.load(urlRequest);
		}
		
		
		private function bindEvent(loader:*):void {
			if (loader is Loader) {
				loader= (loader as Loader).contentLoaderInfo;
			}
			loader.addEventListener(Event.COMPLETE, eventHander);
			loader.addEventListener(IOErrorEvent.IO_ERROR, errorHander);
			loader.addEventListener(ProgressEvent.PROGRESS,eventHander);
		}
		private function removeEvent(loader:*):void {
			loader.removeEventListener(Event.COMPLETE, eventHander);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, errorHander);
			loader.removeEventListener(ProgressEvent.PROGRESS,eventHander);
		}
		
		private function eventHander(event:Event):void {
			switch(event.type) {
				case Event.COMPLETE :
				case Event.INIT :
					removeEvent(event.target);
			}
			dispatchEvent(event.clone());
		}
		
		private function errorHander(event:IOErrorEvent):void {
			dispatchEvent(event);
			trace("crl:"+event);
		}
		
		public function unload():void {
			if (loader is Loader) {
				removeEvent(loader);
				loader.unload();
			}
		}
		public function close():void {
			if (loader is Loader) {
				removeEvent(loader);
				loader.close();
			}
		}
		
		public override function toString():String {
			return this.loader.toString();
		}
		
		
		public function get message():String {
			return this.info;
		}
	}
	
}
